package com.xk.handler.security;

import com.alibaba.fastjson.JSON;
import com.xk.domain.ResponseResult;
import com.xk.enums.AppHttpCodeEnum;

import com.xk.utils.WebUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败异常处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    /**
     *认证过滤器 失败 ,或者 登录认证失败 都调用该方法
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        System.out.println("---认证失败异常处理器---");
        authException.printStackTrace();
        //认证失败后 进行信息提示处理
        ResponseResult result =null;
        switch (authException.getClass().getSimpleName()){
            case "InternalAuthenticationServiceException"://一般账号错误
                result= ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
                break;
            case "BadCredentialsException"://一般密码错误
                result= ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR,authException.getMessage());
                break;
            case "InsufficientAuthenticationException"://一般没有token错误
                result=ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
                break;
            default: //其他不知道什么错误
                result=ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"认证或者授权失败");
        }
        //把错误信息 响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
